 # -*- coding: utf-8 -*-
__author__ = 'yulei'

from igt_push import *
from igetui.template.igt_base_template import *
from igetui.template.igt_transmission_template import *
from igetui.template.igt_link_template import *
from igetui.template.igt_notification_template import *
from igetui.igt_message import *
from igetui.igt_target import *
from igetui.template import *
# import sys
# sys.path.append('..')
import settings
import json
from common import logTool

#toList接口每个用户返回用户状态开关,true：打开 false：关闭
os.environ['needDetails'] = 'false'

def push_message_to_list(push_msg_dict):
    '''
    根据user_list列表进行群发
    oid:mongodb表的id
    title:信息来源
    text:信息正文的前30个字符
    user_list:群发用户cids列表
    msg_type:
    '''

    infotype = int(push_msg_dict.get('infotype','0'))  # 5:短讯  6:资讯
    PType = int(push_msg_dict.get('PType','0'))

    if infotype == 5:
        cliendids = push_msg_dict['cliendids']
        newsFrom = push_msg_dict['newsFrom']  # 短讯是newsFrom
        newskey = push_msg_dict['oid']
        pushDate = push_msg_dict['pushDate']  # 短讯是pushDate
        title = push_msg_dict['content'][0:30]
        #isPublicNews = "0"
        #content = push_msg_dict['content'][0:30]
    elif infotype == 6:
        cliendids = push_msg_dict['cliendids']
        title = push_msg_dict['Title']
        newsFrom = push_msg_dict['NewsFrom']  # 资讯是NewsFrom
        newskey = push_msg_dict['NewsKey']
        pushDate = push_msg_dict['PushDate']  # 资讯是PushDate
        isPublicNews = int(push_msg_dict['IsPublicNews'])
        #content = ""
    else:
        return None

    if infotype == 6:
        if isPublicNews == 1:
            infotype = 8  # 公共信息
        else:
            infotype = 7  # 资讯信息是按热点来推送的,改为7, 方便前端调用newscontent接口来获取正文 7:按热点获取信息正文

    APPKEY = ""
    APPID = ""
    MASTERSECRET = ""

    if PType == 7:
        APPKEY = settings.chem['APPKEY']
        APPID = settings.chem['APPID']
        push = IGeTui(settings.HOST, APPKEY, settings.chem['MASTERSECRET'])
    elif PType == 8:
        APPKEY = settings.agri['APPKEY']
        APPID = settings.agri['APPID']
        push = IGeTui(settings.HOST, APPKEY, settings.agri['MASTERSECRET'])
    elif PType == 9:
        APPKEY = settings.jingang['APPKEY']
        APPID = settings.jingang['APPID']
        push = IGeTui(settings.HOST, APPKEY, settings.jingang['MASTERSECRET'])
    else:
        return None

    template = TransmissionTemplate()  # 透传（payload） 数据经SDK传给您的客户端，由您写代码决定如何处理展现给用户
    template.appId = APPID
    template.appKey = APPKEY
    template.transmissionType = 2      # 收到消息是否立即启动应用，1为立即启动，2则广播等待客户端自启动
    #您需要透传的内容
    template.transmissionContent = '{"id":"%s","title":"%s","NewsFrom":"%s","infotype":"%s","pushDate":"%s"}' \
                                   %(newskey,title,newsFrom,infotype,pushDate)

    # template.transmissionContent = '{"id":"%s","title":"%s","NewsFrom":"%s","infotype":"%s","pushDate":"%s","content":"%s"}' \
    #                                %(newskey,title,newsFrom,infotype,pushDate,content)

    template.title = title
    template.text = newsFrom
    template.isRing = True
    template.isVibrate = True
    template.isClearable = True

    message = IGtListMessage()
    message.data = template
    message.isOffline = True                     # 用户当前不在线时，是否离线存储,可选
    message.offlineExpireTime = 6 * 3600 * 1000  # 离线有效时间，单位为毫秒
    targets=[]
    num=0
    for user in cliendids:
        num += 1
        target = Target()
        target.appId = APPID
        target.clientId = user
        targets.append(target)
        if num % 900 ==0 or num == len(cliendids):  # 每次发送最大控制到900个用户
            contentId = push.getContentId(message)
            ret = push.pushMessageToList(contentId, targets)
            #print ret
            targets=[]


def push_message_to_single(push_msg_dict):
    '''
    对指定的用户进行推送
    oid:mongodb表的id
    title:信息来源
    text:信息正文的前30个字符
    cid:单个用户推送ID
    msg_type:
    '''

    infotype = int(push_msg_dict.get('infotype','0'))  # 5:短讯  6:资讯
    PType = int(push_msg_dict.get('PType','0'))

    if infotype == 5:
        cliendid = push_msg_dict['cliendid']
        title = push_msg_dict['content'][0:30]
        newsFrom = push_msg_dict['newsFrom']
        newskey = push_msg_dict['oid']
        pushDate = push_msg_dict['pushDate']
        #content = push_msg_dict['content'][0:30]
    elif infotype == 6:
        cliendid = push_msg_dict['cliendid']
        title = push_msg_dict['Title']
        newsFrom = push_msg_dict['NewsFrom']
        newskey = push_msg_dict['NewsKey']
        pushDate = push_msg_dict['PushDate']
        isPublicNews = int(push_msg_dict['IsPublicNews'])
        #content = ""
    else:
        return None

    APPKEY = ""
    APPID = ""
    MASTERSECRET = ""

    #infotype = 9  # 暂定

    if infotype == 6:
        if isPublicNews == 1:
            infotype = 8  # 公共信息
        else:
            infotype = 7  # 资讯信息是按热点来推送的,改为7, 方便前端调用newscontent接口来获取正文 7:按热点获取信息正文

    if PType == 7:
        APPKEY = settings.chem['APPKEY']
        APPID = settings.chem['APPID']
        push = IGeTui(settings.HOST, APPKEY, settings.chem['MASTERSECRET'])
    elif PType == 8:
        APPKEY = settings.agri['APPKEY']
        APPID = settings.agri['APPID']
        push = IGeTui(settings.HOST, APPKEY, settings.agri['MASTERSECRET'])
    elif PType == 9:
        APPKEY = settings.jingang['APPKEY']
        APPID = settings.jingang['APPID']
        push = IGeTui(settings.HOST, APPKEY, settings.jingang['MASTERSECRET'])
    else:
        return None

    template =TransmissionTemplate()             # 透传（payload） 数据经SDK传给您的客户端，由您写代码决定如何处理展现给用户
    template.appId = APPID
    template.appKey = APPKEY
    template.transmissionType = 2                # 收到消息是否立即启动应用，1为立即启动，2则广播等待客户端自启动
    template.transmissionContent = '{"id":"%s","title":"%s","NewsFrom":"%s","infotype":"%s","pushDate":"%s"}' \
                                   %(newskey,title,newsFrom,infotype,pushDate)

    # template.transmissionContent = '{"id":"%s","title":"%s","NewsFrom":"%s","infotype":"%s","pushDate":"%s","content":"%s"}' \
    #                                %(newskey,title,newsFrom,infotype,pushDate,content)

    template.title = title
    template.text = newsFrom
    template.isRing = True
    template.isVibrate = True
    template.isClearable = True

    message = IGtSingleMessage()
    message.isOffline = True                     # 用户当前不在线时，是否离线存储,可选
    message.offlineExpireTime = 6 * 3600 * 1000  # 离线有效时间，单位为毫秒
    message.data = template
    target = Target()
    target.appId = APPID
    target.clientId = cliendid

    ret = push.pushMessageToSingle(message, target)

    logTool.create_push_log(json.dumps(ret), u'anroid_work_3.0', push_msg_dict['PType'], push_msg_dict['PushDate'],
                            push_msg_dict['userid'][0], push_msg_dict['Title'], push_msg_dict['NewsKey'])
    return ret